package com.example.demo.controller;

import com.example.demo.entity.Role;
import com.example.demo.entity.User;
import com.example.demo.service.LoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class LoginController {
    @Autowired
    private LoginService loginService;

    //跳转登陆
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login(){
        return "login";
    }
    //登陆
    @RequestMapping(value="/login",method = RequestMethod.POST)
    public String login(Map<String,Object> map){
        //添加用户信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(map.get("username").toString(),map.get("password").toString());
        //进行验证,这里可以捕获异常,返回对应得信息
        subject.login(token);
        return "login";
    }
    //跳转首页
    @RequestMapping("/index")
    public String index(){
        return "index";
    }
    //登出
    @RequestMapping("/logout")
    public String logout(){
        return "/logout";
    }
    //错误页面展示
    @RequestMapping("/error")
    public String error(){
        return "erroe ok";
    }

    //数据初始化
    @RequestMapping(value = "/adduser")
    public String addUser(@RequestBody Map<String,Object> map){
        User user = loginService.addUser(map);
        return "addUser is ok! \n" + user;
    }

    //角色初始化
    @RequestMapping(value = "/addRole")
    public String addRole(@RequestBody Map<String,Object> map){
        Role role = loginService.addRole(map);
        return "addRole is ok ! \n" + role;
    }

    //注解的使用
    @RequiresRoles("admin")
    @RequiresPermissions("create")
    @RequestMapping("/create")
    public String create(){
        return "create success";
    }

}
